package com.shop.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shop.entity.dto.AdminArr.AdminSaveStyleCostArr;
import com.shop.entity.dto.AdminStyle.*;
import com.shop.entity.dto.AdminWares.*;
import com.shop.entity.pojo.*;
import com.shop.admin.mapper.*;
import com.shop.admin.service.StyleService;
import com.shop.utils.common.enums.Code;
import com.shop.utils.common.enums.Message;
import com.shop.utils.common.result.PageResponseResult;
import com.shop.utils.common.result.Result;
import com.shop.utils.config.BaseContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service

public class StyleServiceImpl extends ServiceImpl<StyleMapper,Style> implements StyleService {

    @Autowired
    private CostMapper costMapper;

    @Autowired
    private StyleMapper styleMapper;
    @Autowired
    private AdminUserMapper adminUserMapper;
    @Autowired
    private ImagesMapper waresImagesMapper;
    @Autowired
    private WaresMapper waresMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Result saveOneStyle(AdminStyleSaveDto dto) {
        if (dto==null||
        dto.getCostArr().length==Message.Check_Int_Null) {
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        Long adminId = BaseContext.getCurrentId();
        AdminUser adminUser = adminUserMapper.selectById(adminId);
        if (adminId==null||adminUser==null) {
            return Result.errorResult(Code.NEED_LOGIN);
        }
        Wares wares = waresMapper.selectById(dto.getWaresId());
        List<Style> checkStyleList = styleMapper.selectList(Wrappers.<Style>lambdaQuery()
                .eq(Style::getStyleName, dto.getStyleName()));
        if (checkStyleList!=null&&checkStyleList.size()>Message.Check_Int_Null||wares==null) {
            return Result.errorResult(Code.DATA_EXIST);
        }
        String k=Message.WeChat_Key_Wares+wares.getId();
        redisTemplate.delete(k);

        Images images = waresImagesMapper.selectById(dto.getStyleImagesId());
        Style style=new Style();
        style= style.builder()
                .styleName(dto.getStyleName())
                .styleImages(images.getUrl())
                .waresId(dto.getWaresId())
                .saveAdmin(adminUser.getName())
                .saveTime(String.valueOf(LocalDateTime.now())).build();
        int chekcStyle = styleMapper.saveStyle(style);
        if (chekcStyle== Message.Check_Int_False) {
            return Result.errorResult(Code.SERVER_ERROR);
        }
        Cost cost=new Cost();
        for (AdminSaveStyleCostArr costArr : dto.getCostArr()) {
            cost= cost.builder()
                    .waresId(dto.getWaresId())
                    .styleId(style.getId())
                    .costMessage(costArr.getCostMessage())
                    .waresPrice(costArr.getWaresPrice())
                    .saveAdmin(adminUser.getName())
                    .saveTime(String.valueOf(LocalDateTime.now())).build();
            int checkCost = costMapper.insert(cost);
            if (checkCost== Message.Check_Int_False) {
                styleMapper.deleteById(style);
                return Result.errorResult(Code.SERVER_ERROR);
            }
        }
        redisTemplate.delete(k);
        return Result.okResult(Code.SUCCESS);
    }

    @Override
    public Result getWaresDetail(AdminWaresStyleListDto dto) {
        if (dto==null) {
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        dto.checkParam();
        Page<Style> page=new Page<>(dto.getPage(),dto.getSize());
        Page<Style> value = styleMapper.stylePageByWaresId(page, dto.getWaresId());
        Result result=new PageResponseResult(dto.getPage(),dto.getSize(), (int) value.getTotal());
        result.setData(value.getRecords());
        return result;
    }

    @Override
    public Result updateStyle(AdminStyleUpdateDto dto) {
        if (dto==null) {
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        Long adminId = BaseContext.getCurrentId();
        AdminUser adminUser = adminUserMapper.selectOne(Wrappers.<AdminUser>lambdaQuery().eq(AdminUser::getId, adminId));
        if (adminUser==null||adminId==null) {
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        Style oldStyle = styleMapper.selectById(dto.getStyleId());
        if (oldStyle==null) {
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        String k=Message.WeChat_Key_Wares+oldStyle.getWaresId();
        redisTemplate.delete(k);
        String styleName=oldStyle.getStyleName();
        if (dto.getStyleName()!=null) {
            List<Style> styles = styleMapper.selectList(Wrappers.<Style>lambdaQuery()
                    .eq(Style::getStyleName, dto.getStyleName())
                    .eq(Style::getWaresId,oldStyle.getWaresId()));
            if (styles==null) {
                return Result.errorResult(Code.DATA_EXIST);
            }
            styleName= dto.getStyleName();
        }
        String styleImages=oldStyle.getStyleImages();
        if (dto.getStyleImagesId()!=null) {
            Images waresImages = waresImagesMapper.selectById(dto.getStyleImagesId());
            if (waresImages==null) {
                return Result.errorResult(Code.DATA_NOT_EXIST);
            }
            styleImages=waresImages.getUrl();
        }
        Style style=new Style();
        style= style.builder()
                .styleName(styleName)
                .styleImages(styleImages)
                .saveAdmin(adminUser.getName())
                .saveTime(String.valueOf(LocalDateTime.now())).build();
        boolean update = update(style, Wrappers.<Style>lambdaUpdate().eq(Style::getId, dto.getStyleId()));
        if (!update) {
            return Result.errorResult(Code.SERVER_ERROR);
        }
        redisTemplate.delete(k);
        return Result.okResult(Code.SUCCESS);
    }

    @Override
    public Result removeStyle(AdminStyleRemoveDto dto) {
        if (dto==null) {
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        Long adminId = BaseContext.getCurrentId();
        AdminUser adminUser = adminUserMapper.selectById(adminId);
        if (adminUser==null||adminId==null) {
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        Style style = styleMapper.selectById(dto.getStyleId());
        if (style==null) {
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        String k=Message.WeChat_Key_Wares+style.getWaresId();
        redisTemplate.delete(k);
        List<Cost> costList = costMapper.selectList(Wrappers.<Cost>lambdaQuery().eq(Cost::getStyleId, dto.getStyleId()));
        if (!CollectionUtils.isEmpty(costList)||costList.size()>Message.Check_Int_Null) {
            if (dto.getRemoveRelated().equals(Message.Check_String_True)) {
                boolean removeStyleAsync = removeStyleAsync(adminUser, dto);
                boolean removeStyleCostAsync = removeStyleCostAsync(adminUser, dto);
                if (!removeStyleAsync||!removeStyleCostAsync) {
                    return Result.errorResult(Code.SERVER_ERROR);
                }else {
                    return Result.okResult(Code.SUCCESS);
                }
            }else if (dto.getRemoveRelated().equals(Message.Check_String_False)){
                return Result.errorResult(Code.DATA_EXIST);
            }else {
                return Result.errorResult(Code.PARAM_INVALID);
            }
        }
        boolean styleAsync = removeStyleAsync(adminUser, dto);
        if (!styleAsync) {
            return Result.errorResult(Code.SERVER_ERROR);
        }
        redisTemplate.delete(k);
        return Result.okResult(Code.SUCCESS);
    }

    @Override
    public Result<Style> updateGetStyle(AdminStyleUpdateForGetDto dto) {
        if (dto==null) {
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        Style style = getOne(Wrappers.<Style>lambdaQuery().eq(Style::getId, dto.getStyleId()));
        if (style==null) {
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        return Result.okResult(style);
    }

    @Override
    public Result getStyleList(AdminStyleListDto dto) {
        dto.checkParam();
        Page<Style> page=new Page<>(dto.getPage(),dto.getSize());
        Page<Style> value = styleMapper.getAllByPage(page, dto);
        Result result=new PageResponseResult(dto.getPage(),dto.getSize(), (int) value.getTotal());
        result.setData(value.getRecords());
        return result;
    }

    @Override
    public Result openStyle(AdminStyleOpenDto dto) {
        if (dto.getStyleId()==null) {
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        Long adminId = BaseContext.getCurrentId();
        AdminUser adminUser = adminUserMapper.selectById(adminId);
        Style byId = styleMapper.getOne(dto.getStyleId());
        if (adminId==null||adminUser==null||byId==null) {
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        String k=Message.WeChat_Key_Wares+byId.getWaresId();
        redisTemplate.delete(k);
        if (byId.getIsDelete()==Message.Check_Int_Null) {
            return Result.errorResult(Code.PARAM_INVALID);
        }
        Style style=new Style();
        style= style.builder().id(byId.getId())
                .removeMemo(Message.Remove_Null)
                .removeAdmin(Message.Remove_Null)
                .isDelete(Message.Delete_True)
                .saveAdmin(adminUser.getName())
                .saveTime(String.valueOf(LocalDateTime.now()))
                .version(byId.getVersion()+Message.Version_Up).build();
        boolean update = styleMapper.updateIsDelete(style);
        if (!update) {
            return Result.errorResult(Code.SERVER_ERROR);
        }
        redisTemplate.delete(k);
        return Result.okResult(Code.SUCCESS);
    }

    @Override
    public Result pullStyle(AdminStylePullDto dto) {
        if (dto==null) {
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        Long userId = BaseContext.getCurrentId();
        AdminUser adminUser = adminUserMapper.selectById(userId);
        if (adminUser==null||userId==null) {
            return Result.errorResult(Code.NEED_LOGIN);
        }
        Style checkStyle = styleMapper.selectById(dto.getStyleId());
        if (checkStyle==null) {
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        String k=Message.WeChat_Key_Wares+checkStyle.getWaresId();
        redisTemplate.delete(k);
        boolean asyncStyle = pullAsyncStyle(adminUser, dto);
        boolean asyncStyleCost = pullAsyncStyleCost(adminUser, dto);
        if (!asyncStyle||!asyncStyleCost) {
            return Result.errorResult(Code.SERVER_ERROR);
        }
        redisTemplate.delete(k);
        return Result.okResult(Code.SUCCESS);
    }



    @Override
    public Result putStyle(AdminStylePutDto dto) {
        if (dto==null) {
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        Long userId = BaseContext.getCurrentId();
        AdminUser adminUser = adminUserMapper.selectById(userId);
        if (adminUser==null||userId==null) {
            return Result.errorResult(Code.NEED_LOGIN);
        }
        Style checkStyle = styleMapper.selectById(dto.getStyleId());
        if (checkStyle==null) {
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        String k=Message.WeChat_Key_Wares+checkStyle.getWaresId();
        redisTemplate.delete(k);
        boolean asyncStyle = putAsyncStyle(adminUser, dto);
        boolean asyncStyleCost = putAsyncStyleCost(adminUser, dto);
        if (!asyncStyle||!asyncStyleCost) {
            return Result.errorResult(Code.SERVER_ERROR);
        }
        redisTemplate.delete(k);
        return Result.okResult(Code.SUCCESS);
    }


    /**
     * 异步调用
     */

    //put_style
    @Async
    public boolean putAsyncStyle(AdminUser adminUser,AdminStylePutDto dto){
        boolean check=true;
        Style style=new Style();
        style= style.builder().state(Message.Put)
                .saveAdmin(adminUser.getName())
                .saveTime(String.valueOf(LocalDateTime.now())).build();
        int update = styleMapper.update(style, Wrappers.<Style>lambdaUpdate().eq(Style::getId, dto.getStyleId()));
        if (update== Message.Check_Int_False) {
            check=false;
            return check;
        }
        return check;
    }
    @Async
    public boolean putAsyncStyleCost(AdminUser adminUser,AdminStylePutDto dto){
        boolean check=true;
        Cost cost=new Cost();
        cost=cost.builder()
                .state(Message.Put)
                .saveAdmin(adminUser.getName())
                .saveTime(String.valueOf(LocalDateTime.now())).build();
        int update = costMapper.update(cost, Wrappers.<Cost>lambdaUpdate().eq(Cost::getStyleId, dto.getStyleId()));
        if (update== Message.Check_Int_False) {
            check=false;
            return check;
        }
        return check;
    }



    //pull_style
    @Async
    public boolean pullAsyncStyle(AdminUser adminUser,AdminStylePullDto dto){
        boolean check=true;
        Style style=new Style();
        style= style.builder().state(Message.Pull).removeAdmin(adminUser.getName()).removeMemo(dto.getMemo()).build();
        int update = styleMapper.update(style, Wrappers.<Style>lambdaUpdate().eq(Style::getId, dto.getStyleId()));
        if (update== Message.Check_Int_False) {
            check=false;
            return check;
        }
        return check;
    }
    @Async
    public boolean pullAsyncStyleCost(AdminUser adminUser,AdminStylePullDto dto){
        boolean check=true;
        Cost cost=new Cost();
        cost= cost.builder().state(Message.Pull).removeAdmin(adminUser.getName()).removeMemo(dto.getMemo()).build();
        int update = costMapper.update(cost, Wrappers.<Cost>lambdaUpdate().eq(Cost::getStyleId, dto.getStyleId()));
        if (update== Message.Check_Int_False) {
            check=false;
            return check;
        }
        return check;
    }



    //remove_style
    @Async
    public boolean removeStyleAsync(AdminUser adminUser,AdminStyleRemoveDto dto){
        boolean check=true;
        Style newStyle=new Style();
        newStyle= newStyle.builder()
                .removeMemo(dto.getRemoveMemo())
                .removeAdmin(adminUser.getName()).build();
        int update = styleMapper.update(newStyle, Wrappers.<Style>lambdaUpdate().eq(Style::getId, dto.getStyleId()));
        int delete = styleMapper.deleteById(dto.getStyleId());
        if (update== Message.Check_Int_False||delete==Message.Check_Int_False) {
            check=false;
            return check;
        }
        return check;

    }
    @Async
    public boolean removeStyleCostAsync(AdminUser adminUser,AdminStyleRemoveDto dto){
        boolean check=true;
        Cost cost=new Cost().builder().removeAdmin(adminUser.getName()).removeMemo(dto.getRemoveMemo()).build();
        int update = costMapper.update(cost, Wrappers.<Cost>lambdaQuery().eq(Cost::getStyleId, dto.getStyleId()));
        int delete = costMapper.delete(Wrappers.<Cost>lambdaQuery().eq(Cost::getStyleId, dto.getStyleId()));
        if (update== Message.Check_Int_False||delete==Message.Check_Int_False) {
            check=false;
            return check;
        }
        return check;
    }

}
